// 获取元素的通用函数
function getElement(selector) {
    return document.querySelector(selector);
}

// 更新输入框样式
function updateInputStyle(inputContainer, inputItem) {
    inputContainer.classList.toggle('invalid', inputItem.value === '');
}

// 创建输入框的通用函数
function createInput(config) {
    const { inputContainer, inputItem, toggleIcon } = config;

    // 监听输入框内容是否为空，更新输入框样式
    inputItem.addEventListener('input', () => updateInputStyle(inputContainer, inputItem));

    if (toggleIcon) {
        // 点击切换密码显隐
        toggleIcon.addEventListener('click', () => {
            const isPassword = inputItem.type === 'password';  // 判断当前密码框类型
            inputItem.type = isPassword ? 'text' : 'password';  // 切换密码框类型
            toggleIcon.src = isPassword ? './Image/preview-open.png' : './Image/preview-close-one.png';  // 切换图标
        });
    }
}

// 密码框
createInput({
    inputContainer: getElement('.password-group'),
    inputItem: getElement('#password'),
    toggleIcon: getElement('.invisible')
});

// 用户名框
createInput({
    inputContainer: getElement('.username-group'),
    inputItem: getElement('#username')
});

// 验证码框的封装
let isAbandon = false;
let captchaId = 0;

const captchaContainer = getElement('.captcha-container');
const captchaImg = getElement('.captcha-img');
const expiredText = getElement('#expiredText');

async function loadCaptcha() {
    const captchaResult = await fetchData(`${baseUrl}/api/sysAuth/captcha`, 'GET');
    isAbandon = false;
    captchaImg.src = `data:text/html;base64,${captchaResult.result.img}`;
    captchaId = captchaResult.result.id;
    setTimeout(() => {
        captchaImg.classList.add('abandon');
        expiredText.style.display = 'block';
        isAbandon = true;
    }, captchaResult.result.expirySeconds * 1000);

}

captchaContainer.addEventListener('click', () => {
    loadCaptcha()
    captchaImg.classList.remove('abandon');
    expiredText.style.display = 'none';
});

// 获取输入框的值
function getInputValue(inputID) {
    return getElement(`#${inputID}`).value;
}

// 登录按钮点击事件
const loginBtn = getElement('.login-btn');
loginBtn.addEventListener('click', () => {
    const usernameValue = getInputValue('username');
    const passwordValue = getInputValue('password');
    const captchaValue = getInputValue('captcha');
    fetchRequest('POST', `${baseUrl}/api/sysAuth/login`, {
        account: usernameValue,
        password: passwordValue,
        codeId: isAbandon ? 0 : captchaId,
        code: captchaValue
    })
    .then(result => {
        console.log(result);
    })
    .catch(error => {
        console.error("Request failed:", error);
    });
});

// 初次加载时，加载验证码
window.onload = loadCaptcha;
